// login.js
// 获取应用实例
const app = getApp();
const WXAPI = require('../main/main');
var setTimeOut= null;//延时器
Page({
  data: {
    isNeibu: false,
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
    account: '',
    password: ''
  },
  onLoad() {
    var that = this;
    // if (wx.getUserProfile) {
    //   this.setData({
    //     canIUseGetUserProfile: true
    //   })
    // }
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              //用户已经授权过
              // that.timeOut();//延时器开启
              that.login(0)//0表示自动登陆
              // wx.reLaunch({
              //   url: '../login/login',
              // })
            }
          });
        } else {
           wx.reLaunch({
                url: '../auth/auth',
              })
        }
      }
    })
  },
  // 获取输入账号  
  accountInput: function (e) {
    this.setData({
      account: e.detail.value
    })
  },

  // 获取输入密码  
  passwordInput: function (e) {
    this.setData({
      password: e.detail.value
    })
  },
  // 登录
  login(id){
    var that = this;
    wx.showLoading({
      title: '登录中...',
      icon: 'none',
    });
    //自动登录标识
    app.globalData.auto = true;
    if(id != 0){ 
      if (this.data.account.length == 0 || this.data.password.length == 0) {
        wx.showToast({
          title: '用户名和密码不能为空',
          icon: 'none',
          duration: 2000
        })
        return;
      }
      app.globalData.auto = false;
    }
    //获取用户信息
    wx.login({
      success: function (res) {
        if (res.code) {
          wx.getUserInfo({
            success: function (res) {
              var userInfo = {};
              userInfo.avatarUrl = res.userInfo.avatarUrl;
              userInfo.nickName = res.userInfo.nickName;
              app.globalData.userInfo = userInfo; //存储userInfo
            }
          });
          var goald = app.globalData; //这里存储了appid、secret
          var wxurl = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + goald.appid + '&secret=' + goald.secret + '&js_code=' + res.code + '&grant_type=authorization_code';
          
          WXAPI.login({
            username: that.data.account, //账号
            password: that.data.password, //密码
            wxurl: wxurl,
          }).then(function (result) {
            console.log(result);
            wx.hideLoading();
            if(result.code == 400){
              //欢迎页面隐藏  用户未绑定
              that.setData({
                welcomeflag: false,
              });
              return
            }       
            if (result.code == 403) {
             //登录失败
              wx.showToast({
                title:result.msg,
                icon:'none',
                duration: 2000
              });
              //欢迎页面隐藏
              that.setData({
                welcomeflag:false,
              });
              return;
            } else if (result.code == 200) {
              //登录成功
              wx.setStorageSync('user', result.data.user);
              app.globalData.user = result.data.user;
              app.globalData.bindStatus = result.data.user.bindStatus;
              app.globalData.openId = result.data.openId;
              wx.setStorageSync("token", result.data.token); 
              console.log("登录用户信息：",app.globalData.user);
              console.log("用户绑定状态", app.globalData.user.bindStatus == 0?'【未绑定】':'已绑定');
              console.log("用户openId",app.globalData.openId);
              that.setData({
                loginStatus:true,
              });
              var toUrl = '../insiderView/index/index';  
              wx.showToast({
                title:'登录成功！',
                icon: 'success',
                duration:100
              });
              clearInterval(setTimeOut);//清除定时器
              wx.hideLoading();
              setTimeout(function () {
                wx.reLaunch({
                  url: toUrl,
                })
              }, 50)
            } else{
              if (id!=0){
                wx.showToast({
                  title: result.msg,
                  icon: 'none',
                  duration: 1000
                });
              }
              //欢迎页面隐藏
              that.setData({
                welcomeflag: false,
              })
              wx.hideLoading();
            }
          });
          
        }
      }
    });

    // if(!this.data.hasUserInfo){
    //   this.getUserProfile()
    // }else{
    //   wx.navigateTo({
    //     url: '../insiderView/index/index'
    //   })
    // }
  },
  // 校内人员访问
  insideLogin(){
    this.setData({
      isNeibu: true
    })
  },
  // 访客预约
  outsideLogin(){
    this.setData({
      isNeibu: false
    })
    if(!this.data.hasUserInfo){
      this.getUserProfile()
    }else{
      wx.navigateTo({
        url: '../visitorView/index/index'
      })
    }
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('用户信息', res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        if(this.data.isNeibu){
          wx.navigateTo({
            url: '../insiderView/index/index'
          })
        }else{
          wx.navigateTo({
            url: '../visitorView/index/index'
          })
        }
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  /***登陆超时**/
  timeOut(){
    var that=this;
    setTimeOut=setTimeout(function () {
      if(!that.data.loginStatus && that.data.welcomeflag){
        wx.showToast({
          title: '服务器出现错误!联系管理员处理！',
          icon: 'none',
          duration:10000
        });
      }
    }, 8000);
  },
})
